<template>
    <Page class="content_home" :use-header="true" title="首页">
        <a-card>
            <a-upload :file-list="fileList" :before-upload="handleBeforeUpload" @change="handleChange">
                <a-button type="primary">选择文件</a-button>
            </a-upload>
            <a-divider />
            <a-button type="primary" @click="handleUpload">上传</a-button>
        </a-card>
    </Page>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import Page from '@/component/layout/Page.vue';
import { FileUtil, UUIDUtil, WebSocketUtil } from '@/util';
import Http from '@/axios';
import { ApiFile } from '@/axios/api';
import { Result } from '@/model/common';
import { message } from 'ant-design-vue';

const fileList = ref<object[]>([]);

const handleBeforeUpload = (file: any, fileList: any) => {
    console.log(`file - ${JSON.stringify(file)}`);
    console.log(`fileList - ${JSON.stringify(fileList)}`);
    console.log(`------`);
    return false;
};

const handleChange = (data: { file: any; fileList: any; event: any }) => {
    console.log(`file - ${JSON.stringify(data.file)}`);
    console.log(`fileList - ${JSON.stringify(data.fileList)}`);
    console.log(`event - ${JSON.stringify(data.event)}`);
    console.log(`------`);
    fileList.value = data.fileList;
};

const handleUpload = () => {
    const id = UUIDUtil.uuid();
    const file = (fileList.value[0] as any).originFileObj;
    const chunkSize = 5 * 1024;
    const chunkNum = FileUtil.chunkNum(file, chunkSize);
    let chunkIndex = 1;

    const requestList: Promise<Result>[] = [];
    while (chunkIndex <= chunkNum) {
        const chunkFile = FileUtil.chunk(file, chunkIndex, chunkSize);
        const formData = new FormData();
        formData.append('file', chunkFile, file.name);
        formData.append('index', chunkIndex.toString());
        formData.append('total', chunkNum.toString());
        formData.append('id', id);
        requestList.push(ApiFile.uploadChunkFile(formData));
        chunkIndex++;
    }
    if (requestList.length > 0) {
        Http.all(requestList)
            .then((res: any) => {
                message.success('上传成功');
                console.log(`res - ${JSON.stringify(res)}`);
            })
            .catch((err: Result) => {
                message.error(err.msg);
                console.log(`err - ${JSON.stringify(err)}`);
            });
    }
};
</script>

<style scoped lang="less">
.content_home {
    .ant-card {
        margin-top: 24px;

        &:first-child {
            margin-top: 0;
        }
    }
}
</style>
